package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.Constants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateTimeZoneConverter;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IDeviceService;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;

/**
 * 设备管理Service业务层处理
 *
 * @author ruoyi
 * @date 2025-08-01
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IoTDAClient client;

    @Autowired
    private ElderServiceImpl elderService;

    /**
     * 查询设备上报属性
     *
     * @param iotId 设备ID
     * @return 结果
     */
    @Override
    public List<Map<String, Object>> queryServiceProperties(String iotId) {
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse deviceResponse = client.showDeviceShadow(request);
        if (deviceResponse.getHttpStatusCode() != 200) {
            throw new RuntimeException("查询设备详情失败");
        }
        List<DeviceShadowData> shadow = deviceResponse.getShadow();
        if (ObjectUtils.isEmpty(shadow)) {
            throw new RuntimeException("查询设备详情失败");
        }
        DeviceShadowProperties reported = shadow.get(0).getReported();
        if (ObjectUtils.isEmpty(reported)) {
            throw new RuntimeException("查询设备详情失败");
        }
        Object properties = reported.getProperties();
        String eventTime = reported.getEventTime();
        LocalDateTime time = LocalDateTimeUtil.parse(eventTime, "yyyyMMdd'T'HHmmss'Z'");
        // 时区转换
        LocalDateTime time1 = DateTimeZoneConverter.utcToShanghai(time);
        JSONObject entries = JSONUtil.parseObj(properties);
        List<Map<String, Object>> list = new ArrayList<>();
        entries.forEach((key, value) -> {
            Map<String, Object> map = new HashMap<>();
            map.put("functionId", key);
            map.put("value", value);
            map.put("eventTime", time1);
            list.add(map);
        });
        return list;
    }

    @Override
    public DeviceDetailVo queryDeviceDetail(String iotId) {
        // 查询本地设备数据
        Device device = getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        if (ObjectUtils.isEmpty(device)) {
            return null;
        }
        // 调用华为云接口查询设备详情
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse deviceResponse = client.showDevice(request);
        if (deviceResponse.getHttpStatusCode() != 200) {
            return null;
        }
        DeviceDetailVo detailVo = new DeviceDetailVo();
        BeanUtils.copyProperties(device, detailVo);
        detailVo.setDeviceStatus(deviceResponse.getStatus());
        String activeTime = deviceResponse.getActiveTime();
        //日期转换
        if (StringUtils.isNotEmpty(activeTime)) {
            LocalDateTime time = LocalDateTimeUtil.parse(activeTime, DatePattern.UTC_MS_PATTERN);
            detailVo.setActiveTime(time);
        }
        return detailVo;
    }

    @Override
    public void syncProductList() {
        //请求参数
        ListProductsRequest listProductsRequest = new ListProductsRequest();
        //设置参数
        listProductsRequest.setLimit(50);
        //发起请求
        ListProductsResponse response = client.listProducts(listProductsRequest);
        if (response.getHttpStatusCode() != 200) {
            throw new RuntimeException("同步产品列表失败");
        }
        // 存储到redis
        redisTemplate.opsForValue().set(Constants.IOT_ALL_PRODUCT_LIST, JSONUtil.toJsonStr(response.getProducts()));

    }

    @Override
    public List<ProductVo> selectAllProductList() {
        String products = (String) redisTemplate.opsForValue().get(Constants.IOT_ALL_PRODUCT_LIST);
        if (StringUtils.isEmpty(products)) {
            return Collections.emptyList();
        }
        List<ProductVo> list = JSONUtil.toList(products, ProductVo.class);
        return list;
    }

    /**
     * 注册产品
     *
     * @param dto
     */
    @Override
    public void registerDevice(DeviceDto dto) {
        //1.设备名称是否重复
        long count = count(Wrappers.<Device>lambdaQuery().eq(Device::getDeviceName, dto.getDeviceName()));
        if (count > 0) {
            throw new RuntimeException("设备名称重复");
        }
        //2.设备标识是否重复
        count = count(Wrappers.<Device>lambdaQuery().eq(Device::getNodeId, dto.getNodeId()));
        if (count > 0) {
            throw new RuntimeException("设备标识重复");
        }
        //3.同一位置是否绑定了相同的产品
        count = count(Wrappers.<Device>lambdaQuery()
                .eq(Device::getProductKey, dto.getProductKey())
                .eq(Device::getBindingLocation, dto.getBindingLocation())
                .eq(Device::getLocationType, dto.getLocationType())
                .eq(dto.getPhysicalLocationType() != null, Device::getPhysicalLocationType, dto.getPhysicalLocationType())
        );
        if (count > 0) {
            throw new RuntimeException("同一位置已绑定相同产品");
        }
        //4.注册设备
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        body.setProductId(dto.getProductKey());
        body.setNodeId(dto.getNodeId());
        body.setProductId(dto.getProductKey());

        AuthInfo authInfo = new AuthInfo();
        String secret = UUID.randomUUID().toString().replaceAll("-", "");
        authInfo.setSecret(secret);
        body.setDeviceName(dto.getDeviceName());
        body.setAuthInfo(authInfo);
        request.setBody(body);

        AddDeviceResponse response = client.addDevice(request);
        if (response.getHttpStatusCode() != 201) {
            throw new RuntimeException("设备注册失败");
        }
        //5.保存到数据库
        Device device = new Device();
        BeanUtils.copyProperties(dto, device);
        device.setSecret(secret);
        // 设备id、设备绑定状态
        device.setIotId(response.getDeviceId());
        save(device);
    }

    /**
     * 查询设备管理
     *
     * @param id 设备管理主键
     * @return 设备管理
     *//*
    @Override
    public Device selectDeviceById(Long id) {
        return getById(id);
    }*/

    /**
     * 查询设备管理列表
     *
     * @param device 设备管理
     * @return 设备管理
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 修改设备
     *
     * @param deviceDto
     */
    @Override
    public boolean updateDevice(DeviceDto deviceDto) {
        //3. 根据id查询出设备信息
        Device device = this.getById(deviceDto.getId());
        if (ObjectUtil.isEmpty(device)) {
            throw new BaseException("该设备不存在");
        }
        //如果名称相同，直接抛出异常
        long count1 = this.count(Wrappers.<Device>lambdaQuery()
                .ne(Device::getId, deviceDto.getId())
                .eq(Device::getDeviceName, deviceDto.getDeviceName()));
        if (count1 > 0) {
            throw new BaseException("该设备名称已存在");
        }

        //2. 修改数据库中的设备信息
        //2.1 修改时，不能在同一位置绑定同一个产品
        long count = this.count(Wrappers.<Device>lambdaQuery()
                .ne(Device::getId, deviceDto.getId())//TODO 排除当前设备
                .eq(Device::getProductKey, deviceDto.getProductKey())// 产品key
                .eq(Device::getBindingLocation, deviceDto.getBindingLocation())// 绑定位置
                .eq(Device::getLocationType, deviceDto.getLocationType())// 位置类型
                .eq(deviceDto.getPhysicalLocationType() != null,//随身设备没有此属性
                        Device::getPhysicalLocationType,
                        deviceDto.getPhysicalLocationType()));
        if (count > 0) {
            throw new BaseException("同一个位置上已经绑定了相同的设备");
        }
        //1. 先修改Iot平台上的设备名称
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        request.setDeviceId(device.getIotId());
        UpdateDevice body = new UpdateDevice();
        body.setDeviceName(deviceDto.getDeviceName());
        request.setBody(body);
        UpdateDeviceResponse response = client.updateDevice(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("在华为云IOT平台修改设备名称失败！");
        }
        //2.2 在数据库中进行修改
        Device updateDevice = BeanUtil.toBean(deviceDto, Device.class);
        updateDevice.setIotId(device.getIotId());
        if (updateDevice.getPhysicalLocationType() == null) {
            updateDevice.setDeviceDescription(String.valueOf(deviceDto.getBindingLocation()));
            updateDevice.setPhysicalLocationType(-1);
        }
        boolean flag = this.updateById(updateDevice);
        //设备名称不相同，才去修改Iot平台上的设备名称

        return flag;
    }

    @Override
    public boolean deleteDevice(String iotId) {
        Device device = this.getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        if (ObjectUtil.isEmpty(device)) {
            throw new BaseException("该设备不存在");
        }
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.setDeviceId(iotId);
        DeleteDeviceResponse response = client.deleteDevice(request);
        if (response.getHttpStatusCode() != 204){
            throw new BaseException("在华为云IOT平台删除设备失败！");
        }
        boolean result = removeById(device);
        return result;
    }

    /**
     * 查询设备详细数据
     * @param productKey
     * @return
     */
    @Override
    public List<ServiceCapability> queryProduct(String productKey) {
        ShowProductRequest request = new ShowProductRequest();
        request.setProductId(productKey);
        ShowProductResponse response = client.showProduct(request);
        if (response.getHttpStatusCode() != 200){
            return ListUtil.empty();
        }
        List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();
        if (CollUtil.isNotEmpty(serviceCapabilities)) {
            return serviceCapabilities;
        }
        return serviceCapabilities;
    }


    /* *//**
     * 新增设备管理
     *
     * @param device 设备管理
     * @return 结果
     *//*
    @Override
    public int insertDevice(Device device) {
        return save(device) ? 1 : 0;
    }

    *//**
     * 修改设备管理
     *
     * @param device 设备管理
     * @return 结果
     *//*
    @Override
    public int updateDevice(Device device) {
        return updateById(device) ? 1 : 0;
    }

    *//**
     * 批量删除设备管理
     *
     * @param ids 需要删除的设备管理主键
     * @return 结果
     *//*
    @Override
    public int deleteDeviceByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    *//**
     * 删除设备管理信息
     *
     * @param id 设备管理主键
     * @return 结果
     *//*
    @Override
    public int deleteDeviceById(Long id) {
        return removeById(id) ? 1 : 0;
    }*/
}
